package com.bestcem.xm.user.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author panyun <yun.pan@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/6 15:14
 */
@EnableAsync
@Configuration
public class UserExecutorConfig {

    /**
     * 不可丢弃任务的列表查询线程池
     *
     * @return java.util.concurrent.Executor
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/6 15:17
     */
    @Bean(name = "executor")
    public Executor userMailSendExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池数
        executor.setCorePoolSize(1);
        //最大线程
        executor.setMaxPoolSize(10);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(20);
        // 设置默认线程名称
        executor.setThreadNamePrefix("user-executor-");
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置队列容量
        executor.setQueueCapacity(0);
        //队列满，线程被拒绝执行策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 执行初始化
        executor.initialize();
        return executor;
    }


    @Bean
    public ScheduledThreadPoolExecutor orderUpgradeExecutor() {
        ThreadFactory tf = new CustomizableThreadFactory("order-upgrade-pool-");
        return new ScheduledThreadPoolExecutor(1, tf, new ThreadPoolExecutor.CallerRunsPolicy());
    }

    /**
     * 用户 批量发送激活邮件/激活 线程池配置
     */
    @Bean(name = "user_email_executor")
    public Executor userActiveEmailExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(10);
        // 设置最大线程数
        executor.setMaxPoolSize(20);
        // 设置队列容量
        executor.setQueueCapacity(0);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(60);
        // 拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 设置默认线程名称
        executor.setThreadNamePrefix("xm_user_email_executor");
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 执行初始化
        executor.initialize();
        return executor;
    }

}
